package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.domain.dto.TemplateDTO;
import org.chen.domain.dto.TemplateVariableResponse;
import org.chen.domain.entity.VideoGenerationRecord;
import org.chen.domain.entity.VideoTemplate;
import org.chen.domain.request.VideoGenerationRequest;
import org.chen.domain.vo.TemplateQuery;
import org.chen.domain.vo.VideoRecordQuery;
import org.chen.client.HeyGenClient;
import org.chen.mapper.VideoGenerationRecordMapper;
import org.chen.mapper.VideoTemplateMapper;
import org.chen.response.VideoTemplateStatusResponse;
import org.chen.service.TemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class TemplateServiceImpl extends ServiceImpl<VideoTemplateMapper, VideoTemplate> implements TemplateService {
    private final HeyGenClient heygenClient;
    private final VideoTemplateMapper templateMapper;
    private final VideoGenerationRecordMapper recordMapper;
    private final ObjectMapper objectMapper;

    /**
     * 同步模板
     */
    @Transactional(rollbackFor = Exception.class)
    public String syncTemplates() {
        try {
            // 获取远程模板列表
            List<TemplateDTO> templates = heygenClient.listTemplates();
            int added = 0;
            int updated = 0;

            for (TemplateDTO template : templates) {
                try {
                    // 查询本地是否存在
                    VideoTemplate existTemplate = templateMapper.selectOne(
                            new QueryWrapper<VideoTemplate>()
                                    .eq("template_id", template.getTemplateId())
                    );

                    // 获取模板的变量配置
                    TemplateVariableResponse variableResponse = heygenClient.getTemplateVariables(template.getTemplateId());

                    VideoTemplate videoTemplate = new VideoTemplate();
                    videoTemplate.setTemplateId(template.getTemplateId());
                    videoTemplate.setName(template.getName());
                    videoTemplate.setThumbnailUrl(template.getThumbnailImageUrl());
                    videoTemplate.setVariableConfig(objectMapper.writeValueAsString(variableResponse.getVariables()));
                    videoTemplate.setLastSyncTime(LocalDateTime.now());

                    if (existTemplate != null) {
                        videoTemplate.setId(existTemplate.getId());
                        templateMapper.updateById(videoTemplate);
                        updated++;
                    } else {
                        templateMapper.insert(videoTemplate);
                        added++;
                    }
                } catch (Exception e) {
                    log.error("Failed to sync template: {}", template.getTemplateId(), e);
                }
            }

            return String.format("同步完成：新增 %d 个，更新 %d 个", added, updated);
        } catch (Exception e) {
            log.error("Failed to sync templates", e);
            throw new RuntimeException("同步模板失败: " + e.getMessage());
        }
    }

    /**
     * 获取模板列表
     */
    public Page<VideoTemplate> listTemplates(TemplateQuery query) {
        Page<VideoTemplate> page = new Page<>(query.getPageNum(), query.getPageSize());

        QueryWrapper<VideoTemplate> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(query.getName())) {
            wrapper.like("name", query.getName());
        }
        wrapper.orderByDesc("last_sync_time");

        return templateMapper.selectPage(page, wrapper);
    }

    /**
     * 获取模板详情
     */
    public VideoTemplate getTemplateDetail(String id) {
        return templateMapper.selectById(id);
    }

    /**
     * 从模板生成视频 (补充实现)
     */
    @Transactional(rollbackFor = Exception.class)
    public VideoGenerationRecord generateVideo(VideoGenerationRequest request) {
        // 1. 查询模板
        VideoTemplate template = templateMapper.selectById(request.getTemplateId());
        if (template == null) {
            throw new RuntimeException("模板不存在");
        }

        try {
            // 2. 创建生成记录
            VideoGenerationRecord record = new VideoGenerationRecord();
            record.setTemplateId(template.getTemplateId());
            record.setConfigId(request.getConfigId());
            record.setVariableValues(objectMapper.writeValueAsString(request.getVariables()));
            record.setStatus("PENDING");
            recordMapper.insert(record);

            // 3. 准备API请求参数
            Map<String, Object> requestParams = new HashMap<>();
            requestParams.put("variables", request.getVariables());

            // 添加配置
            if (request.getConfig() != null) {
                if (request.getConfig().containsKey("title")) {
                    requestParams.put("title", request.getConfig().get("title"));
                }

                if (request.getConfig().containsKey("caption")) {
                    requestParams.put("caption", request.getConfig().get("caption"));
                }

                if (request.getConfig().containsKey("test")) {
                    requestParams.put("test", request.getConfig().get("test"));
                }

                if (request.getConfig().containsKey("dimension")) {
                    requestParams.put("dimension", request.getConfig().get("dimension"));
                }
            }

            // 4. 调用HeyGen API生成视频
            String videoId = heygenClient.generateVideo(template.getTemplateId(), requestParams);

            // 5. 更新记录
            record.setVideoId(videoId);
            record.setStatus("PROCESSING");
            recordMapper.updateById(record);

            // 6. 返回记录
            return record;
        } catch (Exception e) {
            log.error("Failed to generate video", e);
            throw new RuntimeException("生成视频失败: " + e.getMessage());
        }
    }

    /**
     * 查询视频生成状态
     */
    public VideoGenerationRecord checkVideoStatus(String recordId) {
        VideoGenerationRecord record = recordMapper.selectById(recordId);
        if (record == null) {
            throw new RuntimeException("生成记录不存在");
        }

        if ("COMPLETED".equals(record.getStatus()) || "FAILED".equals(record.getStatus())) {
            return record;
        }

        try {
            // 调用HeyGen API查询状态
            VideoTemplateStatusResponse response = heygenClient.checkVideoStatus(record.getVideoId());

            // 更新状态
            if ("completed".equalsIgnoreCase(response.getStatus())) {
                record.setStatus("COMPLETED");
                record.setVideoUrl(response.getVideoUrl());
            } else if ("failed".equalsIgnoreCase(response.getStatus())) {
                record.setStatus("FAILED");
                record.setErrorMessage(response.getErrorMessage());
            }

            recordMapper.updateById(record);
            return record;
        } catch (Exception e) {
            log.error("Failed to check video status", e);
            throw new RuntimeException("查询视频状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取生成历史记录
     */
    public Page<VideoGenerationRecord> getGenerationHistory(VideoRecordQuery query) {
        Page<VideoGenerationRecord> page = new Page<>(query.getPageNum(), query.getPageSize());

        QueryWrapper<VideoGenerationRecord> wrapper = new QueryWrapper<>();

        if (StringUtils.hasText(query.getTemplateId())) {
            wrapper.eq("template_id", query.getTemplateId());
        }

        if (StringUtils.hasText(query.getStatus())) {
            wrapper.eq("status", query.getStatus());
        }

        if (query.getStartTime() != null) {
            wrapper.ge("create_time", query.getStartTime());
        }

        if (query.getEndTime() != null) {
            wrapper.le("create_time", query.getEndTime());
        }

        wrapper.orderByDesc("create_time");

        return recordMapper.selectPage(page, wrapper);
    }

    /**
     * 删除生成记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteGenerationRecord(String recordId) {
        VideoGenerationRecord record = recordMapper.selectById(recordId);
        if (record == null) {
            throw new RuntimeException("记录不存在");
        }

        recordMapper.deleteById(recordId);
    }
}
